#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os

from oracle import logger
from oracle.common.common import get_dir_levels
from oracle.common.windows_common import execute_windows_cmd, check_path_in_disk_group


def create_asm_dir(asm_path, asm_instance, oracle_home):
    parts = get_dir_levels(asm_path)
    path_str = parts[0]
    home_path = os.path.join(oracle_home, "BIN")
    for part in parts[1:]:
        path_str = path_str + "/" + part
        if check_path_in_disk_group("", path_str, asm_instance, oracle_home):
            logger.info(f'path_str exits,{path_str}')
            continue
        cmd = f"cmd /c asmcmd mkdir {path_str}"
        os.environ["ORACLE_SID"] = asm_instance
        os.environ["ORACLE_HOME"] = oracle_home
        os.environ["NLS_LANG"] = "American_America.US7ASCII"
        logger.info(f"cmd:{cmd},home_path:{home_path}")
        ret, result = execute_windows_cmd("", cmd.split(), home_path)
        if not ret:
            logger.error(f"create_asm_path {path_str} error,std_out:{ret},std_err:{result}")
            return False
    return True
